package com.example.controller;


import com.example.entity.Admin;
import com.example.result.Result;
import com.example.context.BaseContext;
import com.example.entity.Account;
import com.example.entity.Buyer;
import com.example.exception.CustomException;
import com.example.service.AdminService;
import com.example.service.BuyerService;
import com.example.util.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
//对外接口返回json数据
@Tag(name="身份认证相关接口")
@RequestMapping("/identity")
public class WebController {
    @Resource
    private AdminService adminService;
    @Resource
    private BuyerService buyService;

    @Operation(summary = "买家/卖家登录",description="角色为ADMIN为卖家，BUYER为买家")
    @PostMapping("/login")
    public Result login(@RequestBody Account account){
        Object loginResult=null;
        String token = null;
        if("ADMIN".equals(account.getRole())){//管理员登录
            Admin admin = adminService.login(account);
            token = JwtUtils.generateToken(admin.getId());
            loginResult = admin;
        }else if("BUYER".equals(account.getRole())){//买家登录
            Buyer buyer = buyService.login(account);
            token = JwtUtils.generateToken(buyer.getId());
            loginResult = buyer;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("user", loginResult);
        result.put("token", token);
        return Result.success(result);
    }

    @Operation(summary = "买家注册",description="买家注册信息")
    @PostMapping("/registerBuyer")
    public Result register(@RequestBody Account account){
        buyService.register((Buyer) account);
        return Result.success();
    }
    @Operation(summary = "卖家修改密码",description="卖家修改密码")
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Account account){

        if("ADMIN".equals(account.getRole())){
            adminService.updatePassword(account);

        }else{
            throw new CustomException("500","非法输入");
        }
        return Result.success();
    }
}
